package lumis.service.resourcescheduler;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.portal.PortalException;
import lumis.portal.dao.hibernate.ITransactionHibernate;
import lumis.util.CollectionExecutor;
import lumis.util.TextUtil;

import org.hibernate.Session;
/**
 * Validates the roomIds before delete then. If a roomId belongs a any schedule its not delete.
 * 
 * @version $Revision: 10218 $ $Date: 2009-03-17 20:30:21 -0300 (Tue, 17 Mar 2009) $
 * @since 4.0.10
 */
public class RoomDeleteValidatorProcessActionHandler extends ProcessActionHandler
{
	@SuppressWarnings("unchecked")
	public void processAction() throws PortalException
	{
		String[] roomIds = (String[])getParameter("id");

		ITransactionHibernate transactionHibernate = (ITransactionHibernate)transaction;
		final Session session = transactionHibernate.getSession();

		final HashSet<String> usedRoomIds = new HashSet<String>();
		CollectionExecutor<String> executor = new CollectionExecutor<String>(Arrays.asList(roomIds));
		executor.execute(new CollectionExecutor.IIterationCommand<String>()
		{
			public void execute(List<String> subItems)
			{
				usedRoomIds.addAll(session.createQuery("select distinct schedule.roomId from lumis.service.resourcescheduler.Schedule as schedule where schedule.roomId in (:rooms)")
					.setParameterList("rooms", subItems).list());
			}
		});
		
		if (!usedRoomIds.isEmpty())
		{
			StringBuilder roomNames = new StringBuilder();
			for (String usedRoomId: usedRoomIds)
			{
				Resource resource = (Resource)session.get(Resource.class, usedRoomId);
				if (roomNames.length() > 0)
					roomNames.append(", ");
				roomNames.append("'"+resource.getName()+"'");
			}
			throw new PortalException("STR_ROOMS_IN_USE;" + TextUtil.escapeLocalizationParameter(roomNames.toString()), getResource());
		}
	}
}
